package registry

import (
	"context"
	"fmt"
	"github.com/go-redis/redis"
	"log"
	"project-im/internal/api/response"
	"project-im/tools"
)

// 初始化 Redis 客户端
var rdb *redis.Client
var ctx = context.Background()

func init() {
	rdb = redis.NewClient(&redis.Options{
		Addr: "localhost:6379", // Redis 地址
	})
}

// 批量获取用户的在线终端类型
func GetOnlineTerminal(userIds []int64) map[int64][]tools.IMTerminalType {
	if len(userIds) == 0 {
		return map[int64][]tools.IMTerminalType{}
	}

	// 模拟用户数据存储
	userMap := make(map[string]response.ImResponse)
	for _, id := range userIds {
		for _, terminal := range []tools.IMTerminalType{tools.WEB, tools.APP, tools.PC} {
			key := fmt.Sprintf("%s:%d:%d", "IM_USER_SERVER_ID", id, terminal)
			userMap[key] = response.ImResponse{UserId: id, Terminal: int(terminal)}
		}
	}

	// 批量拉取 Redis 中的值
	keys := make([]string, 0, len(userMap))
	for key := range userMap {
		keys = append(keys, key)
	}

	// 从 Redis 获取批量数据
	serverIds, err := rdb.MGet(keys...).Result()
	if err != nil {
		log.Fatalf("Error fetching data from Redis: %v", err)
		return nil
	}

	// 处理返回的数据
	onlineMap := make(map[int64][]tools.IMTerminalType)
	for idx, key := range keys {
		if serverIds[idx] != nil {
			userInfo := userMap[key]
			terminals := onlineMap[userInfo.UserId]
			terminals = append(terminals, tools.IMTerminalType(userInfo.Terminal))
			onlineMap[userInfo.UserId] = terminals
		}
	}

	// 去重并返回结果
	for id, terminals := range onlineMap {
		// 去重
		uniqueTerminals := make([]tools.IMTerminalType, 0, len(terminals))
		seen := map[tools.IMTerminalType]bool{}
		for _, terminal := range terminals {
			if !seen[terminal] {
				uniqueTerminals = append(uniqueTerminals, terminal)
				seen[terminal] = true
			}
		}
		onlineMap[id] = uniqueTerminals
	}

	return onlineMap
}
